package ru.hh.school.commands;

import ru.hh.school.PrivateMessage;
import ru.hh.school.User;
import ru.hh.school.UserManager;
import ru.hh.school.exceptions.InnerChatException;
import ru.hh.school.exceptions.UserNotFoundException;
import ru.hh.school.logging.Logger;
import ru.hh.school.persistence.DataRepository;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static ru.hh.school.util.ResourceManager.message;

public class PrivCommand extends Command {
    private final DataRepository dataRepository;
    private final Pattern parsePattern = Pattern.compile("^([^ ]+)[ ]+(.+)$");
    private final UserManager userManager;

    public PrivCommand(Logger logger, DataRepository dataRepository, UserManager userManager) {
        super(logger);
        this.dataRepository = dataRepository;
        this.userManager = userManager;
    }

    public String getCommand() {
        return "/priv";
    }

    public String getDescription() {
        return message("command.priv.description");
    }

    // messageData here is "receiver Message"
    public void process(User user, String messageData) throws InnerChatException, InterruptedException {
        Matcher matcher = parsePattern.matcher(messageData);
        if (matcher.matches()) {
            String recipientName = matcher.group(1);
            String message = matcher.group(2);

            try {
                String formattedMessage = message("command.priv.message", user.getLogin(), message);
                long messageId = dataRepository.insertPrivateMessage(formattedMessage, recipientName);
                user.sendMessage(message("command.priv.message.self", user.getLogin(), recipientName, message));
                User receiver = userManager.getUserByLogin(recipientName);
                if (receiver != null) {
                    receiver.sendPrivateMessage(new PrivateMessage(messageId, formattedMessage, receiver.getId()));
                } else {
                    user.sendMessage(message("user.not.online", recipientName));
                }


            } catch (UserNotFoundException e) {
                user.sendMessage(message("command.priv.no.such.user", recipientName));
            }
        } else {
            user.sendMessage(message("command.priv.invalid.format"));
        }

    }
}